package com.base.controller;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.base.bean.CustomBigDecimalEditor;
import com.base.bean.CustomDateEditor;
import com.base.conf.RedisHelper;
import com.base.utils.CookieUtil;
import com.base.vo.LoginUserInfo;

/**
 * @类描述：控制层基类
 * @创建人：wangdw
 * @创建时间：2018年11月7日 上午9:44:41
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    protected RedisHelper redisHelper;
    
    /**
     * 存放token的cookie名称
     */
    public static final String TOKEN_COOKIE_NAME = "AuthorizationToken";
    
    /**
     * 存放用户信息的Redis KEY
     */
    public static final String USER_KEY = "Login_UserInfo:";
    
    /**
     * 方法描述：获取当前登录用户信息（不含菜单权限等信息，避免传输数据过大）
     * @return
     */
    public LoginUserInfo getUserInfo() {
        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ra.getRequest();
        
        String token = CookieUtil.getCookie(request, TOKEN_COOKIE_NAME);
        
        LoginUserInfo userInfo = (LoginUserInfo) redisHelper.get(USER_KEY + token);
        
        return userInfo;
    }
    
    /**
     * 方法描述：自动转换参数类型（对@RequestBody无效）
     * @param binder
     * @throws Exception
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) throws Exception {
        // 处理BigDecimal的自动装载问题
        binder.registerCustomEditor(BigDecimal.class, new CustomBigDecimalEditor());
        // 处理10位日期格式的自动装载问题
        binder.registerCustomEditor(Date.class, new CustomDateEditor());
    }
}
